package com.narbeshuber.tablet.lasalara.http;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

import com.narbeshuber.tablet.lasalara.LasaLaraActivity;
import com.narbeshuber.tablet.lasalara.R;
import com.narbeshuber.tablet.lasalara.fragment.ChapterFragment;
import com.narbeshuber.tablet.lasalara.listadapters.ChapterAdapter;
import com.narbeshuber.tablet.lasalara.model.Chapter;

public class GetChaptersTask extends AsyncTask<String, Object, String>{

	LasaLaraActivity lasalaraActivity;
	ProgressDialog dialog;
	String bookKey;
	public GetChaptersTask(LasaLaraActivity lasalaraActivity){
		this.lasalaraActivity = lasalaraActivity;
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		dialog = ProgressDialog.show(lasalaraActivity, "", "Downloading chapters. Please wait...", true);
	}
	
	@Override
	protected String doInBackground(String... arg0) {
		
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost("http://1.narbeshuber.appspot.com/getmchapters");
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		bookKey = arg0[0];
		nameValuePairs.add(new BasicNameValuePair("bk", bookKey));
		try {
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			InputStream is = response.getEntity().getContent();
			BufferedInputStream bis = new BufferedInputStream(is, 700);				 				
			ByteArrayBuffer baf = new ByteArrayBuffer(20);
			int current = 0;
			while ((current = bis.read()) != -1) {
					baf.append((byte) current);
				}		
			final String retval = new String(baf.toByteArray());
			return retval;
		} catch (Exception e) {
			Log.e("Exception: ", e.getMessage());
		}
		return "";
	}

	 protected void onPostExecute(String result) {
		dialog.dismiss();
		Log.e("minuviga", result);
		try {
			JSONArray o = new JSONArray(result);
			List<Chapter> chapters = new ArrayList<Chapter>();
			lasalaraActivity.getDbHelper().beginTransaction();
			for (int i = 0; i < o.length(); i++) {
				JSONObject jsonChapter = o.getJSONObject(i);	
				Chapter chapter = new Chapter();
				chapter.setChapterKey(jsonChapter.getString("ck"));
				chapter.setBookKey(bookKey);
				chapter.setAuthorName(jsonChapter.getString("name"));
				chapter.setAuthorEmail(jsonChapter.getString("email"));
				chapter.setTitle(jsonChapter.getString("title"));
				chapter.setDr(jsonChapter.getString("dr"));
				chapter.setVersion(jsonChapter.getString("version"));
				chapter.setInstitution(jsonChapter.getString("institution"));
				chapter.setAllowProp(jsonChapter.getString("allowProp"));
				lasalaraActivity.getDbHelper().insertChapter(chapter);
			}
			chapters = lasalaraActivity.getDbHelper().getAllChaptersFromBook(bookKey);
			lasalaraActivity.getDbHelper().endTransaction();
	        FragmentManager fragmentManager = lasalaraActivity.getFragmentManager();
			FragmentTransaction fragmentTransaction = fragmentManager
					.beginTransaction();
			ChapterFragment chapterFragment = ChapterFragment.getInstance();
			chapterFragment.setListAdapter(new ChapterAdapter(lasalaraActivity, chapters));
			fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
			fragmentTransaction.replace(R.id.left, chapterFragment);
			fragmentTransaction.commit();
		} catch (JSONException e) {
			Log.e("Exception: ", e.getMessage());
		}
     }
}
